//
//  StoreDetailViewController.m
//  com.modada.new
//
//  Created by ferver7 on 2019/5/5.
//  Copyright © 2019 ferver7. All rights reserved.
//

#import "StoreDetailViewController.h"
#import "StoreInfoItem.h"
#import "StoreInfoCCell.h"
#import "HomeGoodItemCCell.h"
#import "CBSegmentView.h"
#import "AppKindsModel.h"
#import "ShopKindItem.h"
#import "AddCartOrBuyView.h"
#import "MDDGoodsDetailViewController.h"
#import "UIView+LLXAlertPop.h"
#import "StoreMapShowViewController.h"

@interface StoreDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,AxcBannerViewDataSource,AxcBannerViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *selfCollectionView;
@property (nonatomic, strong) AxcUI_BannerView *bannerView;
@property (nonatomic,strong) StoreInfoItem *storeItem;

@property (nonatomic,assign) NSInteger page;
@property (nonatomic,strong) NSMutableArray *allGoodItems;
@property (nonatomic,strong) NSString *key;
@property (nonatomic,strong) NSString *partId;
@property (nonatomic,strong) NSMutableArray *kindsArr;
@property (nonatomic, strong) CBSegmentView *zoomSegmentView;
@end

@implementation StoreDetailViewController
-(void)rightAction:(UIButton *)sender
{
    
    if ([[AppUserBaseModel sharedUserData].phone isEqualToString:@"13975856648"]) {//游客模式的判断
        [[NSNotificationCenter defaultCenter] postNotificationName:@"appUserOutLogin" object:nil];
        return;
    }
    
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    setDickeyobj(parameters, self.storeId, @"storeid");
    setDickeyobj(parameters, @"1", @"add");
    if ([self.storeItem.isCollection isEqualToString:@"0"]) {
        setDickeyobj(parameters, @"true", @"isStar");
    }else{
        setDickeyobj(parameters, @"false", @"isStar");
    }
    [PPNetworkHelper POST:app_person_collectionStore parameters:parameters success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            if ([self.storeItem.isCollection isEqualToString:@"0"]) {
                self.storeItem.isCollection = @"1";
            }else{
                self.storeItem.isCollection = @"0";
            }
            if ([self.storeItem.isCollection isEqualToString:@"0"]) {
//                [self addRightBarButtonWithFirstImage:mImageByName(@"爱心") action:@selector(rightAction:)];
                [self addRightBarButtonItemWithTitleAndTitleWithleft:@"收藏" withImage:[UIImage imageNamed:@"爱心"] action:@selector(rightAction:)];

            }else{
//                [self addRightBarButtonWithFirstImage:mImageByName(@"爱心2") action:@selector(rightAction:)];
                [self addRightBarButtonItemWithTitleAndTitleWithleft:@"收藏" withImage:[UIImage imageNamed:@"爱心2"] action:@selector(rightAction:)];

            }
        }else{
            
        }
        
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    mNavitationTitle(@"店铺详情");
    self.view.backgroundColor = [UIColor AxcUI_colorWithHexCode:@"#ebebeb"];
    [self customNavigationItems];
    [self addRightBarButtonWithFirstImage:mImageByName(@"爱心") action:@selector(rightAction:)];
    [self loadStoreDetail];
    self.selfCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadAllGoods];
    }];
    self.selfCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadAllGoods];
    }];
    self.allGoodItems = [[NSMutableArray alloc]init];
    [self loadAllGoods];
    WS(weakSelf);
    self.zoomSegmentView.titleChooseReturn = ^(NSInteger x) {
        NSLog(@"点击了第%ld个按钮",x+1);
        if (x == 0) {
            weakSelf.key = nil;
            weakSelf.partId = nil;
        }else{
            NSDictionary * infoDic = weakSelf.storeItem.classifyingList[x-1];
            weakSelf.key = infoDic[@"fiId"];
            weakSelf.partId = infoDic[@"parentId"];
        }
        weakSelf.page = 1;
        [weakSelf loadAllGoods];
    };
}
#pragma mark -
#pragma mark - **************** collectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 2) {
        return self.allGoodItems.count;
    }
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UICollectionViewCell * adCell = mGetCollectionViewCell(@"adCCell", indexPath);
        [adCell addSubview:self.bannerView];
//        [self.bannerView AxcUI_reloadData];
        return adCell;
    }
    if (indexPath.section == 1) {
        StoreInfoCCell * storeInfoCell = mGetCollectionViewCell(@"storeInfoCCell", indexPath);
        storeInfoCell.phoneActionBlock = ^{
            NSArray *arrayTitle = [self.storeItem.telphone componentsSeparatedByString:@","];
            UIColor *color = [UIColor AxcUI_colorWithHexCode:@"#676767"];
            [self.view createAlertViewTitleArray:arrayTitle textColor:color font:[UIFont systemFontOfSize:16] actionBlock:^(UIButton * _Nullable button, NSInteger didRow) {
                //获取点击事件
                NSLog(@"%@,%ld",button.currentTitle,(long)didRow);
//                lab.text = [NSString stringWithFormat:@"%@,下标%ld",button.currentTitle,(long)didRow];
                NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", button.currentTitle];
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
                } else {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
                }
            }];
        };
        storeInfoCell.daoHangActionBlock = ^{
            StoreMapShowViewController * smsvc = [[StoreMapShowViewController alloc]init];
            smsvc.storeItem = self.storeItem;
            NavigationController_pushVC(smsvc);
        };
        [storeInfoCell reloadViewForModel:self.storeItem];
        return storeInfoCell;
    }
    if (indexPath.section == 2) {
        HomeGoodItemCCell * itemCellMoudle = mGetCollectionViewCell(@"homeGoodItemCCell", indexPath);
        AppBaseGoodItem * itemModel = self.allGoodItems[indexPath.row];
        itemCellMoudle.goodItem = itemModel;
        itemCellMoudle.addCartBlock = ^{//app_shoppingCart_insert
            AddCartOrBuyView * popView = [[[NSBundle mainBundle] loadNibNamed:@"AddCartOrBuyView" owner:self options:nil] firstObject];
            popView.axcUI_Size = CGSizeMake(mScreenWidth, mScreenHeight*2/3);
            popView.goodItem = itemModel;
            popView.pushRoot = self;
            [GKCover translucentCoverFrom:mKeyWindow content:popView animated:YES];
        };
        return itemCellMoudle;
    }
    return nil;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.section == 2) {
            AppBaseGoodItem  * itemModel = self.allGoodItems[indexPath.row];
            MDDGoodsDetailViewController * detailVC = mGetStoryboardViewController(@"Main", @"mDDGoodsDetailViewController");
            detailVC.goodId = itemModel.gid;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
    // 要先设置表头大小
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGSizeMake(0, 0);
    }
    if (section == 1) {
        return CGSizeMake(0, 0);
    }
    if (section == 2) {
        return CGSizeMake(mScreenWidth, 46);
    }
    if (section == 3) {
        return CGSizeMake(mScreenWidth, 44);
    }
    return CGSizeMake(0, 0);
}
    
- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
    {
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            if (indexPath.section == 0) {
                return nil;
            }
            if (indexPath.section == 2) {
                UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCollectionView" forIndexPath:indexPath];
                [headerView addSubview:self.zoomSegmentView];
                return headerView;
            }
        }
        
        return nil;
    }
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ) {
        return CGSizeMake(mScreenWidth,mScreenWidth*150/345);
    }else if (indexPath.section == 1 ) {
        return CGSizeMake(mScreenWidth,150);
    }else if (indexPath.section == 2 ) {
       return CGSizeMake((mScreenWidth-15)/2,(mScreenWidth-15)*0.5+95);
    }else if (indexPath.section == 3 ) {
        return CGSizeMake((mScreenWidth-45)/2,(mScreenWidth-45)*3/8+65);
    }else{
        return CGSizeMake(0, 0);
    }
    
}
    //这个是两行cell之间的间距（上下行cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0 ) {
        return 0;
    }else if (section == 1 ) {
        return 0;
    }else if (section == 2 ) {
        return 5;
    }else if (section == 3 ) {
        return 15;
    }else{
        return 12;
    }
}
    //两个cell之间的间距（同一行的cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0 ) {
        return 0;
    }else if (section == 1 ) {
        return 0;
    }else if (section == 2 ) {
        return 5;
    }else if (section == 3 ) {
        return 15;
    }else{
        return 12;
    }
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 0 ) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }else if (section == 1 ) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }else if (section == 2 ) {
        return UIEdgeInsetsMake(5, 5, 0, 5);
    }else if (section == 3 ) {
        return UIEdgeInsetsMake(0, 15, 0, 15);
    }else{
        return UIEdgeInsetsMake(12, 12, 12, 12);
    }
}
#pragma mark AxcBannerViewDataSource
    // 返回 Banner 需要显示 Item(View) 的个数
- (NSInteger)AxcUI_numberOfItemsInBanner:(AxcUI_BannerView *)banner{
    NSArray * imageArr = [self.storeItem.shuffingImages componentsSeparatedByString:@","];
    return imageArr.count;
}
    
    // 返回 Banner 在不同的 index 所要显示的 View (可以是完全自定义的v iew, 且无需设置 frame)
- (UIView *)AxcUI_banner:(AxcUI_BannerView *)banner viewForItemAtIndex:(NSInteger)index{
    NSArray * imageArr = [self.storeItem.shuffingImages componentsSeparatedByString:@","];
    NSString *imageName = imageArr[index];
    // 创建将要显示控件
    UIImageView *imageView = [[UIImageView alloc] init];
    // 加载图片，返回任意View即可，这里使用网络加载图片展示简单轮播
    [imageView sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:nil];
    
    //    imageView.contentMode = UIViewContentModeScaleAspectFill;
    
    return imageView;
}
    // 当self.bannerView.axcUI_showFooter = YES 的时候才会回调这个委托
- (void)AxcUI_bannerFooterDidTrigger:(AxcUI_BannerView *)banner{
    NSLog(@"触发了footer");
    
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view.backgroundColor = [UIColor AxcUI_CloudColor];
    vc.title = @"新测试VC";
    [self.navigationController pushViewController:vc animated:YES];
}
    
- (void)AxcUI_banner:(AxcUI_BannerView *)banner didSelectItemAtIndex:(NSInteger)index{
    NSLog(@"点击了第%zi个View",index);
    
}
    
    // 返回 Footer 在不同状态时要显示的文字
- (NSString *)AxcUI_banner:(AxcUI_BannerView *)banner titleForFooterWithState:(AxcBannerFooterState)footerState{
    if (footerState == AxcBannerFooterStateIdle) {
        return @"拖动进入下一页";
    } else if (footerState == AxcBannerFooterStateTrigger) {
        return @"释放进入下一页";
    }
    return nil;
}
#pragma mark -
#pragma mark - **************** 数据请求
-(void)loadStoreDetail
{
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    setDickeyobj(parameters, self.storeId, @"storeId");
    setDickeyobj(parameters, @"1", @"add");
    [PPNetworkHelper POST:app_mall_storeInfo parameters:parameters success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            self.storeItem = [[StoreInfoItem alloc]init];
            [self.storeItem setValuesForKeysWithDictionary:responseObject[@"data"][@"storeInfo"]];
            
            for (NSDictionary * infoDic in self.storeItem.classifyingList) {
                AppKindsModel * model = [[AppKindsModel alloc]init];
                model.name = infoDic[@"typeName"];
                model.ID = infoDic[@"cfId"];
                [self.kindsArr addObject:model];
                [self.zoomSegmentView setTitleArray:self.kindsArr withStyle:CBSegmentStyleSlider];
            }
            if ([self.storeItem.isCollection isEqualToString:@"0"]) {
//                [self addRightBarButtonWithFirstImage:mImageByName(@"爱心") action:@selector(rightAction:)];
               [self addRightBarButtonItemWithTitleAndTitleWithleft:@"收藏" withImage:[UIImage imageNamed:@"爱心"] action:@selector(rightAction:)];
            }else{
//                [self addRightBarButtonWithFirstImage:mImageByName(@"爱心2") action:@selector(rightAction:)];
                [self addRightBarButtonItemWithTitleAndTitleWithleft:@"收藏" withImage:[UIImage imageNamed:@"爱心2"] action:@selector(rightAction:)];

            }
        }else{
            
        }
        [self.selfCollectionView reloadData];
        [self.bannerView AxcUI_reloadData];
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}
-(void)loadAllGoods
{
    if ([self.selfCollectionView.mj_header isRefreshing]) {
        self.page = 1;
    }
    if ([self.selfCollectionView.mj_footer isRefreshing]) {
        self.page ++;
    }
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    setDickeyobj(parameters, @"10", @"limit");
    NSString * pageStr = [NSString stringWithFormat:@"%ld",self.page];
    setDickeyobj(parameters, pageStr, @"page");
    setDickeyobj(parameters, self.storeId, @"storeId");
    if (self.key) {
        setDickeyobj(parameters, self.key, @"key");
    }
    if (self.partId) {
        setDickeyobj(parameters, self.partId, @"parentId");
    }
    [PPNetworkHelper POST:app_mall_getGoodsInStore parameters:parameters success:^(id responseObject) {
        [self.selfCollectionView.mj_header endRefreshing];
        [self.selfCollectionView.mj_footer endRefreshing];
        if (self.page == 1 && self.allGoodItems.count > 0) {
            [self.allGoodItems removeAllObjects];
        }
        if (YJPPSUCCESS(responseObject)) {
            for (NSDictionary * dataD in responseObject[@"data"][@"list"]) {
                AppBaseGoodItem * item = [[AppBaseGoodItem alloc]init];
                [item setValuesForKeysWithDictionary:dataD];
                [self.allGoodItems addObject:item];
            }
            if ([responseObject[@"data"][@"list"] count] < 10) {
                [self.selfCollectionView.mj_footer endRefreshingWithNoMoreData];
                
            }
        }else{
            
        }
        [self.selfCollectionView reloadData];
    } failure:^(NSError *error) {
        [self.selfCollectionView.mj_header endRefreshing];
        [self.selfCollectionView.mj_footer endRefreshing];
    } showLoading:nil];
}
#pragma mark - 懒加载区
- (AxcUI_BannerView *)bannerView{
    if (!_bannerView) {
        _bannerView = [[AxcUI_BannerView alloc] initWithFrame:CGRectMake(0, 0, mScreenWidth, mScreenWidth*150/345)];
        _bannerView.axcUI_bannerDataSource = self;
        _bannerView.axcUI_bannerDelegate = self;
        _bannerView.axcUI_shouldLoop = YES;
        _bannerView.axcUI_autoScroll = YES;
        // 设置frame
    }
    return _bannerView;
}
#pragma mark -
#pragma mark - **************** lazyLoad
-(CBSegmentView *)zoomSegmentView{
    if (!_zoomSegmentView) {
        _zoomSegmentView = [[CBSegmentView alloc]initWithFrame:CGRectMake(0, 1, mScreenWidth, 44)];
        _zoomSegmentView.backgroundColor = [UIColor whiteColor];
    }
    return _zoomSegmentView;
}
-(NSMutableArray *)kindsArr
{
    if (!_kindsArr) {
        _kindsArr = [[NSMutableArray alloc]init];
        [_kindsArr addObject:@"全部"];
    }
    return _kindsArr;
}
@end
